import os
import re
import subprocess
import getpath
import sys
def runCmd(cmd):
    from subprocess import Popen, PIPE, STDOUT
    p = Popen(cmd, stdout=PIPE, stdin=PIPE, stderr=STDOUT)
def mylistdir(p,fileStr):
    walk_tree = os.walk(p)
    fs=[]
    for root, subFolders, files in walk_tree:
        for file in files:
            if filepattern(file,fileStr):
                fs.append((root,file))
    return(fs)
def filepattern(filename,p):
    p1=p.replace(".",r"\.")
    p2=p1.replace("*",".*")
    p2=p2+"$"
    if  re.search(p2,filename,re.IGNORECASE)==None :
       return False
    else:
       return True
def getfiles():
    return mylistdir(".","*.ui")
def uiCone(f):    
    (root,filename)=f
    f=os.path.splitext(filename)
    src=os.path.join(root,f[0]+".ui")
    des=os.path.join(root,"ui_"+f[0]+".py")
    if sys.platform == "linux":
        cmd='pyuic5  %s>%s' %(src,des)
    else:    
        exe=r'f:\Python310\scripts\PyQt5-uic.exe'# % getpath.getdrive()
        if os.path.exists(exe):
            cmd=r"""%s %s>%s""" % (exe,src,des)
        else:
            exe=r'%s\Python38\scripts\pyuic5.exe' % getpath.getdrive()
            cmd=r"""%s %s>%s""" % (exe,src,des)
    print(cmd)
    os.system(cmd)
    return cmd
def uic():
    fs=getfiles()
    # print(fs)
    for f in fs:
        uiCone(f)
def getfiles_rc():
    return mylistdir(".","*.qrc")
def rCone(f):        
    (root,filename)=f
    f=os.path.splitext(filename)
    src=os.path.join(root,f[0]+".qrc")
    des=os.path.join(root,f[0]+"_rc.py")
    if sys.platform == "linux":
        cmd=r'pyrcc5  %s>%s' %(src,des)
    else:
        exe=r'f:\Python310\scripts\PyQt5-rcc.exe' # % getpath.getdrive()
        if os.path.exists(exe):
            cmd=r"""%s %s>%s""" % (exe,src,des)
        else:
            exe=r'%s\Python38\scripts\pyrcc5.exe' % getpath.getdrive()
            cmd=r"""%s %s >%s""" % (exe,src,des)
    print(cmd)
    os.system(cmd)
    return cmd
def rc():
    fs=getfiles_rc()
    for f in fs:
        rCone(f)
if __name__=="__main__":
    uic()
    rc()
